package com.fanilycar51.mvp.common;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.ButterKnife;

/**
 * 创建日期：2017/7/25  16:40
 * 描述:实现懒加载的Fragment
 * 作者:张伟
 */

public abstract class LazyFragment extends Fragment {
    protected boolean isVisible;

    // 标志位，标志已经初始化完成。
    private boolean isPrepared;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(getLayoutId(), container, false);
        ButterKnife.bind(this,view);
//        initView(view);
        isPrepared = true;
        lazyLoad();
        //注册EventBus
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        return view;
    }

//    protected abstract void initView(View view);

    /**
     * 在这里实现Fragment数据的缓加载.
     *
     * @param isVisibleToUser
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            isVisible = true;
            onVisible();
        } else {
            isVisible = false;
            onInvisible();
        }
    }

    protected void onVisible() {
        lazyLoad();
    }

    protected  void lazyLoad(){
        if(!isPrepared || !isVisible) {
            return;
        }
        initData();
    }


    public abstract int getLayoutId();
    protected abstract void initData();
    protected void onInvisible() {
    }

    /**
     * EventBus的接受事件的方法
     *
     * @param busInfo
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void busEvent(BusInfo busInfo) {

    }


    @Override
    public void onDestroy() {
        //解绑操作
//        ButterKnife.unbind(this);
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

}
